home *** CD-ROM | disk | FTP | other *** search
/ Turnbull China Bikeride / Turnbull China Bikeride - Disc 2.iso / STUTTGART / SOUND / MP3CONV / !MP3Conv / c / common next >
Text File  |  1997-04-01  |  48KB  |  1,675 lines

  1. /**********************************************************************
  2.  * ISO MPEG Audio Subgroup Software Simulation Group (1996)
  3.  * ISO 13818-3 MPEG-2 Audio Decoder - Lower Sampling Frequency Extension
  4.  *
  5.  * $Id: common.c,v 1.2 1996/03/28 03:13:37 rowlands Exp $
  6.  *
  7.  * $Log: common.c,v $
  8.  * Revision 1.2  1996/03/28 03:13:37  rowlands
  9.  * Merged layers 1-2 and layer 3 revisions
  10.  *
  11.  * Revision 1.1  1996/02/14 03:45:52  rowlands
  12.  * Initial revision
  13.  *
  14.  * Received from FhG
  15.  **********************************************************************/
  16. /**********************************************************************
  17.  *   date   programmers         comment                               *
  18.  * 2/25/91  Doulas Wong,        start of version 1.0 records          *
  19.  *          Davis Pan                                                 *
  20.  * 5/10/91  W. Joseph Carter    Created this file for all common      *
  21.  *                              functions and global variables.       *
  22.  *                              Ported to Macintosh and Unix.         *
  23.  *                              Added Jean-Georges Fritsch's          *
  24.  *                              "bitstream.c" package.                *
  25.  *                              Added routines to handle AIFF PCM     *
  26.  *                              sound files.                          *
  27.  *                              Added "mem_alloc()" and "mem_free()"  *
  28.  *                              routines for memory allocation        *
  29.  *                              portability.                          *
  30.  *                              Added routines to convert between     *
  31.  *                              Apple SANE extended floating point    *
  32.  *                              format and IEEE double precision      *
  33.  *                              floating point format.  For AIFF.     *
  34.  * 02jul91 dpwe (Aware Inc)     Moved allocation table input here;    *
  35.  *                              Tables read from subdir TABLES_PATH.  *
  36.  *                              Added some debug printout fns (Write*)*
  37.  * 7/10/91 Earle Jennings       replacement of the one float by FLOAT *
  38.  *                              port to MsDos from MacIntosh version  *
  39.  * 8/ 5/91 Jean-Georges Fritsch fixed bug in open_bit_stream_r()      *
  40.  *10/ 1/91 S.I. Sudharsanan,    Ported to IBM AIX platform.           *
  41.  *         Don H. Lee,                                                *
  42.  *         Peter W. Farrett                                           *
  43.  *10/3/91  Don H. Lee           implemented CRC-16 error protection   *
  44.  *                              newly introduced functions are        *
  45.  *                              I_CRC_calc, II_CRC_calc and           *
  46.  *                              update_CRC. Additions and revisions   *
  47.  *                              are marked with dhl for clarity       *
  48.  *10/18/91 Jean-Georges Fritsch fixed bug in update_CRC(),            *
  49.  *                              II_CRC_calc() and I_CRC_calc()        *
  50.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  51.  *                              important fixes involved changing     *
  52.  *                              16-bit ints to long or unsigned in    *
  53.  *                              bit alloc routines for quant of 65535 *
  54.  *                              and passing proper function args.     *
  55.  *                              Removed "Other Joint Stereo" option   *
  56.  *                              and made bitrate be total channel     *
  57.  *                              bitrate, irrespective of the mode.    *
  58.  *                              Fixed many small bugs & reorganized.  *
  59.  * 3/20/92 Jean-Georges Fritsch  fixed bug in start-of-frame search   *
  60.  * 6/15/92 Juan Pineda          added refill_buffer(bs) "n"           *
  61.  *                              initialization                        *
  62.  * 7/08/92 Susanne Ritscher     MS-DOS, MSC6.0 port fixes             *
  63.  * 7/27/92 Mike Li               (re-)Port to MS-DOS                  *
  64.  * 8/19/92 Soren H. Nielsen     Fixed bug in I_CRC_calc and in        *
  65.  *                              II_CRC_calc.  Added function: new_ext *
  66.  *                              for better MS-DOS compatability       *
  67.  * 3/10/93 Kevin Peterson       changed aiff_read_headers to handle   *
  68.  *                              chunks in any order.  now returns     *
  69.  *                              position of sound data in file.       *
  70.  * 3/31/93 Jens Spille          changed IFF_* string compares to use  *
  71.  *                              strcmp()                              *
  72.  * 5/30/93 Masahiro Iwadare     removed the previous modification     *
  73.  *                              for UNIX.                             *
  74.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  75.  *         Daniel Lauzon, and                                         *
  76.  *         Bill Truerniet                                             *
  77.  *--------------------------------------------------------------------*
  78.  *  8/24/93 Masahiro Iwadare    Included IS modification in Layer III.*
  79.  *                              Changed for 1 pass decoding.          *
  80.  *  9/07/93 Toshiyuki Ishino    Integrated Layer III with Ver 3.9.    *
  81.  *--------------------------------------------------------------------*
  82.  * 11/20/93 Masahiro Iwadare    Integrated Layer III with Ver 4.0.    *
  83.  *--------------------------------------------------------------------*
  84.  *  7/14/94 Juergen Koller      rewind of bitbuffer added             *
  85.  *--------------------------------------------------------------------*
  86.  *  6/12/95 Soeren H. Nielsen   Bug fix in new_ext().                 *
  87.  *  7/11/95 Soeren H. Nielsen   Changes for MPEG-2 LSF Layer I and II *
  88.  *--------------------------------------------------------------------*
  89.  * 12/16/96 Johan Hagman    Adapted for Solaris (mpeg3play 0.9)   *
  90.  **********************************************************************/
  91.  
  92. /***********************************************************************
  93. *
  94. *  Global Include Files
  95. *
  96. ***********************************************************************/
  97.  
  98. #include        "common.h"
  99.  
  100. #ifdef  MACINTOSH
  101.  
  102. #include        <SANE.h>
  103. #include        <pascal.h>
  104.  
  105. #endif
  106.  
  107. #include    <string.h> /* 1995-07-11 shn */
  108. #include    <ctype.h>
  109.  
  110. /*-- Local declarations --*/
  111.  
  112. unsigned long         sstell(Bit_stream_struc *);
  113.  
  114. /*-- External references --*/
  115.  
  116. extern char        *programName;
  117. extern Arguments_t     Arguments;
  118.  
  119. /***********************************************************************
  120. *
  121. *  Global Variable Definitions
  122. *
  123. ***********************************************************************/
  124.  
  125. char *mode_names[5] = { "stereo", "j-stereo", "dual-ch", "single-ch" , "multi-ch"};
  126. char *layer_names[3] = { "I", "II", "III" };
  127. char *version_names[2] = { "MPEG-2 LSF", "MPEG-1" };
  128.  
  129. /* 1: MPEG-1, 0: MPEG-2 LSF, 1995-07-11 shn */
  130. double s_freq[2][4] = {{22.05, 24, 16, 0}, {44.1, 48, 32, 0}};
  131.  
  132. /* 1: MPEG-1, 0: MPEG-2 LSF, 1995-07-11 shn */
  133. int     bitrate[2][3][15] = {{
  134.           {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256},
  135.           {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160},
  136.           {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160}},
  137.    
  138.           {{0,32,64,96,128,160,192,224,256,288,320,352,384,416,448},
  139.           {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384},
  140.           {0,32,40,48,56,64,80,96,112,128,160,192,224,256,320}
  141.           }};
  142.  
  143. REAL FAR multiple[64] = {
  144. 2.00000000000000, 1.58740105196820, 1.25992104989487,
  145. 1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
  146. 0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
  147. 0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
  148. 0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
  149. 0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
  150. 0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
  151. 0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
  152. 0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
  153. 0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
  154. 0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
  155. 0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
  156. 0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
  157. 0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
  158. 0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
  159. 0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
  160. 1E-20
  161. };
  162.  
  163. /***********************************************************************
  164. *
  165. *  Global Function Definitions
  166. *
  167. ***********************************************************************/
  168.  
  169. #ifndef BUILTIN_TABLES
  170.  
  171. /* The system uses a variety of data files.  By opening them via this
  172.    function, we can accommodate various locations. */
  173.  
  174. FILE *OpenTableFile(char *name)
  175. {
  176. char fulname[80];
  177. char *envdir;
  178. FILE *f;
  179.  
  180.      fulname[0] = '\0';
  181.  
  182. #ifdef TABLES_PATH
  183.        strcpy(fulname, TABLES_PATH);   /* default relative path for tables */
  184. #endif /* TABLES_PATH */          /* (includes terminal path seperator */
  185.  
  186. #ifdef UNIX                       /* envir. variables for UNIX only */
  187.        {
  188.         char *getenv();
  189.  
  190.         envdir = getenv(MPEGTABENV);   /* check for environment */
  191.         if(envdir != NULL)
  192.             strcpy(fulname, envdir);
  193.         strcat(fulname, PATH_SEPARATOR);  /* add a "/" on the end */
  194.       }
  195. #endif /* UNIX */
  196.  
  197.     strcat(fulname, name);
  198.     if( (f=fopen(fulname,"r"))==NULL ) {
  199.         fprintf(stderr,"OpenTable: could not find %s\n", fulname);
  200.  
  201. #ifdef UNIX
  202.           if(envdir != NULL)
  203.             fprintf(stderr,"Check %s directory '%s'\n",MPEGTABENV, envdir);
  204.           else
  205.             fprintf(stderr,"Check local directory './%s' or setenv %s\n",
  206.                     TABLES_PATH, MPEGTABENV);
  207. #else /* not unix : no environment variables */
  208.  
  209. #ifdef TABLES_PATH
  210.             fprintf(stderr,"Check local directory './%s'\n",TABLES_PATH);
  211. #endif /* TABLES_PATH */
  212.  
  213. #endif /* UNIX */
  214.  
  215.     }
  216.     return f;
  217. }
  218.  
  219.  
  220. /***********************************************************************
  221.  *
  222.  * Read one of the data files ("alloc_*") specifying the bit allocation/
  223.  * quatization parameters for each subband in layer II encoding
  224.  *
  225.  **********************************************************************/
  226.  
  227. int read_bit_alloc(    /* read in table, return # subbands */
  228.     int         table,
  229.     al_table    *alloc)
  230. {
  231.     unsigned int a, b, c, d, i, j;
  232.     FILE    *fp;
  233.     char     name[16], t[80];
  234.     int         sblim;
  235.  
  236.     strcpy(name, "alloc_0");
  237.  
  238.     switch (table) {
  239.     case 0:
  240.     name[6] = '0';
  241.     break;
  242.     case 1:
  243.     name[6] = '1';
  244.     break;
  245.     case 2:
  246.     name[6] = '2';
  247.     break;
  248.     case 3:
  249.     name[6] = '3';
  250.     break;
  251.     case 4:
  252.     name[6] = '4';
  253.     break;        /* LSF, added 1995-07-11 shn */
  254.     default:
  255.     name[6] = '0';
  256.     }
  257.  
  258.     if (!(fp = OpenTableFile(name))) {
  259.     fprintf(stderr, "Please check bit allocation table %s\n", name);
  260.     exit(1);
  261.     }
  262.  
  263.     /*if (Arguments.verbose)*/
  264.     /*      printf("using bit allocation table %s\n", name);*/
  265.  
  266.     fgets(t, 80, fp);
  267.     sscanf(t, "%d\n", &sblim);
  268.     while (!feof(fp)) {
  269.     fgets(t, 80, fp);
  270.     sscanf(t, "%d %d %d %d %d %d\n", &i, &j, &a, &b, &c, &d);
  271.     (*alloc)[i][j].steps = a;
  272.     (*alloc)[i][j].bits  = b;
  273.     (*alloc)[i][j].group = c;
  274.     (*alloc)[i][j].quant = d;
  275.     }
  276.     fclose(fp);
  277.     return sblim;
  278. }
  279. #endif /* BUILTIN_TABLES*/
  280.  
  281.  
  282. /***********************************************************************
  283.  *
  284.  * Using the decoded info the appropriate possible quantization per
  285.  * subband table is loaded
  286.  *
  287.  **********************************************************************/
  288.  
  289. int pick_table(        /* choose table, load if necess, return # sb's */
  290.     frame_params *fr_ps)
  291. {
  292.         int table, lay, ws, bsp, br_per_ch, sfrq,ver;
  293.         int sblim = fr_ps->sblimit;     /* return current value if no load */
  294.              
  295.     ver = fr_ps->header->version;
  296.         lay = fr_ps->header->lay - 1;
  297.         bsp = fr_ps->header->bitrate_index;
  298.         br_per_ch = bitrate[ver][lay][bsp] / fr_ps->stereo;
  299.         ws = fr_ps->header->sampling_frequency;
  300.         sfrq = (int)s_freq[ver][ws];
  301.  
  302.         /* decision rules refer to per-channel bitrates (kbits/sec/chan) */
  303.     if (fr_ps->header->version == MPEG_AUDIO_ID) { /* MPEG-1 */
  304.         if ((sfrq == 48 && br_per_ch >= 56) ||
  305.         (br_per_ch >= 56 && br_per_ch <= 80)) table = 0;
  306.         else if (sfrq != 48 && br_per_ch >= 96) table = 1;
  307.         else if (sfrq != 32 && br_per_ch <= 48) table = 2;
  308.         else table = 3;
  309.     }
  310.     else { /* MPEG-2 LSF */
  311.         table = 4;
  312.     }
  313.  
  314.         if (fr_ps->tab_num != table) {
  315.            if (fr_ps->tab_num >= 0)
  316.               mem_free((void **)&(fr_ps->alloc));
  317.            fr_ps->alloc = (al_table FAR *) mem_alloc(sizeof(al_table),
  318.                                                          "alloc");
  319.            sblim = read_bit_alloc(fr_ps->tab_num = table, fr_ps->alloc);
  320.         }
  321.         return sblim;
  322. }
  323.  
  324.  
  325. int js_bound(int lay, int m_ext)
  326. {
  327. static int jsb_table[3][4] =  { { 4, 8, 12, 16 }, { 4, 8, 12, 16},
  328.                                 { 0, 4, 8, 16} };  /* lay+m_e -> jsbound */
  329.  
  330.     if(lay<1 || lay >3 || m_ext<0 || m_ext>3) {
  331.         fprintf(stderr, "js_bound bad layer/modext (%d/%d)\n", lay, m_ext);
  332.         exit(1);
  333.     }
  334.     return(jsb_table[lay-1][m_ext]);
  335. }
  336.  
  337. /*
  338.  * Interpret data in hdr str to fields in fr_ps
  339.  */
  340. void hdr_to_frps(
  341.     frame_params *fr_ps)
  342. {
  343.     layer *hdr = fr_ps->header;        /* (or pass in as arg?) */
  344.  
  345.     fr_ps->actual_mode = hdr->mode;
  346.     fr_ps->stereo = (hdr->mode == MPG_MD_MONO) ? 1 : 2;
  347.     if (hdr->lay == 2)
  348.     fr_ps->sblimit = pick_table(fr_ps);
  349.     else
  350.     fr_ps->sblimit = SBLIMIT;
  351.     if (hdr->mode == MPG_MD_JOINT_STEREO)
  352.         fr_ps->jsbound = js_bound(hdr->lay, hdr->mode_ext);
  353.     else
  354.         fr_ps->jsbound = fr_ps->sblimit;
  355.     /* alloc, tab_num set in pick_table */
  356. }
  357.  
  358.  
  359. void WriteHdr(frame_params *fr_ps, FILE *s)
  360. {
  361. layer *info = fr_ps->header;
  362.  
  363.    fprintf(s,
  364.     "hdr: s=FFF, id=%X, l=%X, ep=%s, br=%X, sf=%X, pd=%X, ",
  365.         info->version, info->lay,
  366.         ((info->error_protection) ? "on" : "off"),
  367.         info->bitrate_index, info->sampling_frequency, info->padding);
  368.    fprintf(s, "pr=%X, m=%X, js=%X, c=%X,\n",
  369.         info->extension, info->mode, info->mode_ext, info->copyright);
  370.    fprintf(s, "     o=%X, e=%X, alg=%s, layer=%s, tot bitrate=%d, sfrq=%.2f\n",
  371.         info->original, info->emphasis, version_names[info->version],
  372.         layer_names[info->lay-1],
  373.         bitrate[info->version][info->lay-1][info->bitrate_index],
  374.         s_freq[info->version][info->sampling_frequency]);
  375.    fprintf(s, "     mode=%s, sblim=%d, jsbd=%d, ch=%d\n",
  376.        mode_names[info->mode], fr_ps->sblimit, fr_ps->jsbound, fr_ps->stereo);
  377.    fflush(s);
  378. }
  379.  
  380.  
  381. void WriteBitAlloc(unsigned int bit_alloc[2][SBLIMIT],
  382.     frame_params *f_p, FILE *s)
  383. {
  384. int i,j;
  385. int st = f_p->stereo;
  386. int sbl = f_p->sblimit;
  387. int jsb = f_p->jsbound;
  388.  
  389.     fprintf(s, "BITA ");
  390.     for(i=0; i<sbl; ++i) {
  391.     if(i == jsb) fprintf(s,"-");
  392.         for(j=0; j<st; ++j)
  393.             fprintf(s, "%1x", bit_alloc[j][i]);
  394.     }
  395.     fprintf(s, "\n");   fflush(s);
  396. }
  397.  
  398.  
  399. void WriteScale(unsigned int bit_alloc[2][SBLIMIT],
  400.     unsigned int scfsi[2][SBLIMIT], unsigned int scalar[2][3][SBLIMIT],
  401.     frame_params *fr_ps, FILE *s)
  402. {
  403. int stereo  = fr_ps->stereo;
  404. int sblimit = fr_ps->sblimit;
  405. int lay     = fr_ps->header->lay;
  406. int i, j, k;
  407.  
  408.     if (lay == 2) {
  409.         fprintf(s, "SFSI ");
  410.         for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  411.         if (bit_alloc[k][i])  fprintf(s,"%d",scfsi[k][i]);
  412.         fprintf(s, "\nSCFs ");
  413.         for (k=0;k<stereo;k++) {
  414.         for (i=0;i<sblimit;i++)
  415.             if (bit_alloc[k][i])
  416.             switch (scfsi[k][i]) {
  417.               case 0: for (j=0;j<3;j++)
  418.                   fprintf(s,"%2d%c",scalar[k][j][i],
  419.                       (j==2)?';':'-');
  420.                   break;
  421.               case 1:
  422.               case 3: fprintf(s,"%2d-",scalar[k][0][i]);
  423.                   fprintf(s,"%2d;",scalar[k][2][i]);
  424.                   break;
  425.               case 2: fprintf(s,"%2d;",scalar[k][0][i]);
  426.             }
  427.         fprintf(s, "\n");
  428.         }
  429.     }
  430.     else {     /* lay == 1 */
  431.         fprintf(s, "SCFs ");
  432.         for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  433.         if (bit_alloc[k][i])  fprintf(s,"%2d;",scalar[k][0][i]);
  434.         fprintf(s, "\n");
  435.     }
  436. }
  437.  
  438.  
  439. void WriteSamples(int ch, unsigned int FAR sample[SBLIMIT],
  440.     unsigned int bit_alloc[SBLIMIT], frame_params *fr_ps, FILE *s)
  441. {
  442. int i;
  443. int stereo = fr_ps->stereo;
  444. int sblimit = fr_ps->sblimit;
  445.  
  446.     fprintf(s, "SMPL ");
  447.     for (i=0;i<sblimit;i++)
  448.         if ( bit_alloc[i] != 0)
  449.             fprintf(s, "%d:", sample[i]);
  450.     if (ch==(stereo-1) )    fprintf(s, "\n");
  451.     else            fprintf(s, "\t");
  452. }
  453.  
  454.  
  455. int NumericQ(char *s) /* see if a string lookd like a numeric argument */
  456. {
  457. char    c;
  458.  
  459.     while( (c = *s++)!='\0' && isspace((int)c)) /* strip leading ws */
  460.         ;
  461.     if( c == '+' || c == '-' )
  462.         c = *s++;               /* perhaps skip leading + or - */
  463.     return isdigit((int)c);
  464. }
  465.  
  466.  
  467. int BitrateIndex(    /* convert bitrate in kbps to index */
  468.     int ver,        /* 1 or 2 */
  469.     int layr,
  470.     int bRate)        /* legal rates from 32 to 448 */
  471. {
  472. int     index = 0;
  473. int     found = 0;
  474.  
  475.     while(!found && index<15)    {
  476.     if(bitrate[ver][layr-1][index] == bRate)
  477.         found = 1;
  478.     else
  479.         ++index;
  480.     }
  481.     if(found)
  482.     return(index);
  483.     else {
  484.     fprintf(stderr, "BitrateIndex: %d (layer %d) is not a legal bitrate\n",
  485.         bRate, layr);
  486.     return(-1);    /* Error! */
  487.     }
  488. }
  489.  
  490.  
  491. int SmpFrqIndex(    /* convert samp frq in Hz to index */
  492.     long sRate,        /* legal rates 16000, 22050, 24000, 32000, 44100, 48000 */
  493.     int  *version)
  494. {
  495.     if (sRate == 44100L) {
  496.     *version = MPEG_AUDIO_ID; return(0);
  497.     }
  498.     else if (sRate == 48000L) {
  499.     *version = MPEG_AUDIO_ID; return(1);
  500.     }
  501.     else if (sRate == 32000L) {
  502.     *version = MPEG_AUDIO_ID; return(2);
  503.     }
  504.     else if (sRate == 24000L) {
  505.     *version = MPEG_PHASE2_LSF; return(1);
  506.     }
  507.     else if (sRate == 22050L) {
  508.     *version = MPEG_PHASE2_LSF; return(0);
  509.     }
  510.     else if (sRate == 16000L) {
  511.     *version = MPEG_PHASE2_LSF; return(2);
  512.     }
  513.     else {
  514.     fprintf(stderr, "SmpFrqIndex: %ld is not a legal sample rate\n", sRate);
  515.     return(-1);     /* Error! */
  516.     }
  517. }
  518.  
  519.  
  520. /*******************************************************************************
  521. *
  522. *  Allocate number of bytes of memory equal to "block".
  523. *
  524. *******************************************************************************/
  525.  
  526. void  FAR *mem_alloc(unsigned long block, char *item)
  527. {
  528.     void    *ptr;
  529.  
  530. #ifdef    MACINTOSH
  531.     ptr = NewPtr(block);
  532. #endif
  533.  
  534. #ifdef MSC60
  535.     /*ptr = (void FAR *) _fmalloc((unsigned int)block);*/ /* far memory, 92-07-08 sr */
  536.     ptr = (void FAR *) malloc((unsigned int)block); /* far memory, 93-08-24 ss */
  537. #endif
  538.  
  539. #if ! defined (MACINTOSH) && ! defined (MSC60)
  540.     ptr = (void FAR *) malloc(block);
  541. #endif
  542.  
  543.     if (ptr != NULL){
  544. #ifdef    MSC60
  545.     _fmemset(ptr, 0, (unsigned int)block); /* far memory, 92-07-08 sr */
  546. #else
  547.     memset(ptr, 0, block);
  548. #endif
  549.     }
  550.     else {
  551.     fprintf(stderr, "Unable to allocate %s\n", item);
  552.     exit(0);
  553.     }
  554.     return(ptr);
  555. }
  556.  
  557.  
  558. /****************************************************************************
  559. *
  560. *  Free memory pointed to by "*ptr_addr".
  561. *
  562. *****************************************************************************/
  563.  
  564. void    mem_free(void **ptr_addr)
  565. {
  566.     if (*ptr_addr != NULL){
  567. #ifdef  MACINTOSH
  568.         DisposPtr(*ptr_addr);
  569. #else
  570.         free(*ptr_addr);
  571. #endif
  572.         *ptr_addr = NULL;
  573.     }
  574.  
  575. }
  576.  
  577. /*******************************************************************************
  578. *
  579. *  Check block of memory all equal to a single byte, else return FALSE
  580. *
  581. *******************************************************************************/
  582.  
  583. int memcheck(char *array,
  584.     int test,    /* but only tested as a char (bottom 8 bits) */
  585.     int num)
  586. {
  587.     int i=0;
  588.  
  589.     while (array[i] == test && i<num) i++;
  590.     if (i==num) return TRUE;
  591.     else return FALSE;
  592. }
  593.  
  594.  
  595. /*****************************************************************************
  596. *
  597. *  Routines to determine byte order and swap bytes
  598. *
  599. *****************************************************************************/
  600. enum byte_order NativeByteOrder = order_unknown;
  601.  
  602. enum byte_order DetermineByteOrder()
  603. {
  604.     char s[ sizeof(long) + 1 ];
  605.     union
  606.     {
  607.         long longval;
  608.         char charval[ sizeof(long) ];
  609.     } probe;
  610.     probe.longval = 0x41424344L;  /* ABCD in ASCII */
  611.     strncpy( s, probe.charval, sizeof(long) );
  612.     s[ sizeof(long) ] = '\0';
  613.     /* fprintf( stderr, "byte order is %s\n", s ); */
  614.     if ( strcmp(s, "ABCD") == 0 )
  615.         return order_bigEndian;
  616.     else
  617.         if ( strcmp(s, "DCBA") == 0 )
  618.             return order_littleEndian;
  619.         else
  620.             return order_unknown;
  621. }
  622.  
  623. void SwapBytesInWords(short *loc, int words)
  624. {
  625.     int           i;
  626.     unsigned char *src = (unsigned char *)loc;
  627.     unsigned char  tmp;
  628.  
  629.     for (i = 0; i < words; i++) {
  630.     tmp = src[0];
  631.     src[0] = src[1];
  632.     src[1] = tmp;
  633.     src += 2;
  634.     }
  635. }
  636.  
  637. /*****************************************************************************
  638.  *
  639.  *  Read Audio Interchange File Format (AIFF) headers.
  640.  *
  641.  *****************************************************************************/
  642.  
  643. int aiff_read_headers(FILE *file_ptr, IFF_AIFF *aiff_ptr)
  644. {
  645.     int chunkSize, subSize, sound_position;
  646.     
  647.     if ( fseek(file_ptr, 0, SEEK_SET) != 0 )
  648.         return -1;
  649.     
  650.     if ( Read32BitsHighLow(file_ptr) != IFF_ID_FORM )
  651.         return -1;
  652.     
  653.     chunkSize = Read32BitsHighLow( file_ptr );
  654.     
  655.     if ( Read32BitsHighLow(file_ptr) != IFF_ID_AIFF )
  656.         return -1;
  657.     
  658.     sound_position = 0;
  659.     while ( chunkSize > 0 )
  660.     {
  661.         chunkSize -= 4;
  662.         switch ( Read32BitsHighLow(file_ptr) )
  663.     {
  664.             
  665.           case IFF_ID_COMM:
  666.             chunkSize -= subSize = Read32BitsHighLow( file_ptr );
  667.             aiff_ptr->numChannels = Read16BitsHighLow( file_ptr );
  668.             subSize -= 2;
  669.             aiff_ptr->numSampleFrames = Read32BitsHighLow( file_ptr );
  670.             subSize -= 4;
  671.             aiff_ptr->sampleSize = Read16BitsHighLow( file_ptr );
  672.             subSize -= 2;
  673.             aiff_ptr->sampleRate  = ReadIeeeExtendedHighLow( file_ptr );
  674.             subSize -= 10;
  675.             while ( subSize > 0 )
  676.         {
  677.                 getc( file_ptr );
  678.                 subSize -= 1;
  679.         }
  680.             break;
  681.             
  682.           case IFF_ID_SSND:
  683.             chunkSize -= subSize = Read32BitsHighLow( file_ptr );
  684.             aiff_ptr->blkAlgn.offset = Read32BitsHighLow( file_ptr );
  685.             subSize -= 4;
  686.             aiff_ptr->blkAlgn.blockSize = Read32BitsHighLow( file_ptr );
  687.             subSize -= 4;
  688.             sound_position = ftell( file_ptr ) + aiff_ptr->blkAlgn.offset;
  689.             if ( fseek(file_ptr, (long) subSize, SEEK_CUR) != 0 )
  690.                 return -1;
  691.             aiff_ptr->sampleType = IFF_ID_SSND;
  692.             break;
  693.             
  694.           default:
  695.             chunkSize -= subSize = Read32BitsHighLow( file_ptr );
  696.             while ( subSize > 0 )
  697.         {
  698.                 getc( file_ptr );
  699.                 subSize -= 1;
  700.         }
  701.             break;
  702.     }
  703.     }
  704.     return sound_position;
  705. }
  706.  
  707. /*****************************************************************************
  708.  *
  709.  *  Seek past some Audio Interchange File Format (AIFF) headers to sound data.
  710.  *
  711.  *****************************************************************************/
  712.  
  713. int aiff_seek_to_sound_data(FILE *file_ptr)
  714. {
  715.     if ( fseek(file_ptr, AIFF_FORM_HEADER_SIZE + AIFF_SSND_HEADER_SIZE, SEEK_SET) != 0 )
  716.         return(-1);
  717.     return 0;
  718. }
  719.  
  720. /*****************************************************************************
  721.  *
  722.  *  Write Audio Interchange File Format (AIFF) headers.
  723.  *
  724.  *****************************************************************************/
  725.  
  726. int aiff_write_headers(FILE *file_ptr, IFF_AIFF *aiff_ptr)
  727. {
  728.     int chunkSize;
  729.     int sampleBytes = (aiff_ptr->sampleSize / 8) +
  730.               (aiff_ptr->sampleSize % 8 ? 1 : 0);
  731.  
  732.     /* Seek back to beginning    */
  733.     if (fseek(file_ptr, 0L, SEEK_SET) != 0)
  734.     return -1;
  735.     
  736.     /* Write FORM chunk */
  737.     chunkSize = 8 + 18 + 8 + aiff_ptr->numChannels *
  738.             aiff_ptr->numSampleFrames * sampleBytes;
  739.     Write32BitsHighLow( file_ptr, IFF_ID_FORM );
  740.     Write32BitsHighLow( file_ptr, chunkSize );
  741.     Write32BitsHighLow( file_ptr, IFF_ID_AIFF );
  742.     /* Write COMM chunk */
  743.     Write32BitsHighLow( file_ptr, IFF_ID_COMM );
  744.     Write32BitsHighLow( file_ptr, 18 );        /* chunk size*/
  745.     Write16BitsHighLow( file_ptr, aiff_ptr->numChannels );
  746.     Write32BitsHighLow( file_ptr, aiff_ptr->numSampleFrames );
  747.     Write16BitsHighLow( file_ptr, aiff_ptr->sampleSize );
  748.     WriteIeeeExtendedHighLow( file_ptr, aiff_ptr->sampleRate );
  749.     /* Write SSND chunk header */
  750.     chunkSize = 8 + aiff_ptr->numChannels * aiff_ptr->numSampleFrames *
  751.             sampleBytes;
  752.     Write32BitsHighLow( file_ptr, IFF_ID_SSND );
  753.     Write32BitsHighLow( file_ptr, chunkSize );
  754.     Write32BitsHighLow( file_ptr, 0 );        /* offset*/
  755.     Write32BitsHighLow( file_ptr, 0 );        /* block size*/
  756.     return 0;
  757. }
  758.  
  759.  
  760. /*****************************************************************************
  761. *
  762. *  bit_stream.c package
  763. *  Author:  Jean-Georges Fritsch, C-Cube Microsystems
  764. *
  765. *****************************************************************************/
  766.  
  767. /********************************************************************
  768.   This package provides functions to write (exclusive or read)
  769.   information from (exclusive or to) the bit stream.
  770.  
  771.   If the bit stream is opened in read mode only the get functions are
  772.   available. If the bit stream is opened in write mode only the put
  773.   functions are available.
  774. ********************************************************************/
  775.  
  776. /*open_bit_stream_w(); open the device to write the bit stream into it    */
  777. /*open_bit_stream_r(); open the device to read the bit stream from it     */
  778. /*close_bit_stream();  close the device containing the bit stream         */
  779. /*alloc_buffer();      open and initialize the buffer;                    */
  780. /*desalloc_buffer();   empty and close the buffer                         */
  781. /*back_track_buffer();     goes back N bits in the buffer                 */
  782. /*unsigned int get1bit();  read 1 bit from the bit stream                 */
  783. /*unsigned long getbits(); read N bits from the bit stream                */
  784. /*unsigned long byte_ali_getbits();   read the next byte aligned N bits from*/
  785. /*                                    the bit stream                        */
  786. /*unsigned long look_ahead(); grep the next N bits in the bit stream without*/
  787. /*                            changing the buffer pointer                   */
  788. /*put1bit(); write 1 bit from the bit stream  */
  789. /*put1bit(); write 1 bit from the bit stream  */
  790. /*putbits(); write N bits from the bit stream */
  791. /*byte_ali_putbits(); write byte aligned the next N bits into the bit stream*/
  792. /*unsigned long sstell(); return the current bit stream length (in bits)    */
  793. /*int end_bs(); return 1 if the end of bit stream reached otherwise 0       */
  794. /*int seek_sync(); return 1 if a sync word was found in the bit stream      */
  795. /*                 otherwise returns 0                                      */
  796.  
  797. /* refill the buffer from the input device when the buffer becomes empty    */
  798. void refill_buffer(Bit_stream_struc *bs)    /* bit stream structure */
  799. {
  800.     int            i = bs->buf_size - 2 - bs->buf_byte_idx;
  801.     unsigned long    n = 1;
  802.     int            index = 0;
  803.     char        val[2];
  804.  
  805. #ifdef OPTIMIZE
  806.  
  807. #   define RBUFSIZE        8192
  808.     static unsigned char    readbuf[RBUFSIZE];
  809.  
  810.     if (bs->format == BINARY) {
  811.  
  812.     while (i >= 0 && (!bs->eob)) {
  813.         int j;
  814.  
  815.         /* Try to read many bytes in each call to fread()*/
  816.         if (i > RBUFSIZE)
  817.         n = fread(readbuf, sizeof(unsigned char), RBUFSIZE, bs->pt);
  818.         else
  819.         n = fread(readbuf, sizeof(unsigned char), i + 1, bs->pt);
  820.  
  821.         /* Copy the read buffer*/
  822.         for (j = 0; i >= 0 && j < n; j++)
  823.         bs->buf[i--] = readbuf[j];
  824.  
  825.         if (n == 0 && feof(bs->pt))
  826.         bs->eob = i + 1;    /* eof*/
  827.     }
  828.  
  829.     } else {
  830.     while ((i>=0) && (!bs->eob)) {
  831.         while((index < 2) && n) {
  832.         n = fread(&val[index], sizeof(char), 1, bs->pt);
  833.         switch (val[index]) {
  834.         case 0x30:
  835.         case 0x31:
  836.         case 0x32:
  837.         case 0x33:
  838.         case 0x34:
  839.         case 0x35:
  840.                 case 0x36:
  841.                 case 0x37:
  842.                 case 0x38:
  843.                 case 0x39:
  844.                 case 0x41:
  845.                 case 0x42:
  846.                 case 0x43:
  847.                 case 0x44:
  848.                 case 0x45:
  849.                 case 0x46:
  850.                     index++;
  851.                     break;
  852.                 default:
  853.             break;
  854.         }
  855.         }
  856.  
  857.         if (val[0] <= 0x39)
  858.         bs->buf[i] = (val[0] - 0x30) << 4;
  859.         else
  860.         bs->buf[i] = (val[0] - 0x37) << 4;
  861.  
  862.         if (val[1] <= 0x39)
  863.         bs->buf[i--] |= (val[1] - 0x30);
  864.         else
  865.         bs->buf[i--] |= (val[1] - 0x37);
  866.         index = 0;
  867.  
  868.         if (!n)
  869.         bs->eob= i+1;
  870.     }
  871.     }
  872.  
  873. #else
  874.     /* Original code*/
  875.  
  876.     while ((i>=0) && (!bs->eob)) {
  877.     if (bs->format == BINARY)
  878.         n = fread(&bs->buf[i--], sizeof(unsigned char), 1, bs->pt);
  879.         else {
  880.         while((index < 2) && n) {
  881.         n = fread(&val[index], sizeof(char), 1, bs->pt);
  882.         switch (val[index]) {
  883.         case 0x30:
  884.         case 0x31:
  885.         case 0x32:
  886.         case 0x33:
  887.         case 0x34:
  888.         case 0x35:
  889.                 case 0x36:
  890.                 case 0x37:
  891.                 case 0x38:
  892.                 case 0x39:
  893.                 case 0x41:
  894.                 case 0x42:
  895.                 case 0x43:
  896.                 case 0x44:
  897.                 case 0x45:
  898.                 case 0x46:
  899.                     index++;
  900.                     break;
  901.                 default:
  902.             break;
  903.         }
  904.         }
  905.  
  906.         if (val[0] <= 0x39)
  907.         bs->buf[i] = (val[0] - 0x30) << 4;
  908.         else
  909.         bs->buf[i] = (val[0] - 0x37) << 4;
  910.  
  911.         if (val[1] <= 0x39)
  912.         bs->buf[i--] |= (val[1] - 0x30);
  913.         else
  914.         bs->buf[i--] |= (val[1] - 0x37);
  915.         index = 0;
  916.     }
  917.     if (!n)
  918.         bs->eob= i+1;
  919.     }
  920. #endif /* OPTIMIZE*/
  921. }
  922.  
  923. #if BS_FORMAT != BINARY
  924. static char *he = "0123456789ABCDEF";
  925. #endif
  926.  
  927. /*
  928.  * Empty the buffer to the output device when the buffer becomes full
  929.  */
  930. void empty_buffer(
  931.     Bit_stream_struc *bs,   /* bit stream structure */
  932.     int minimum)        /* end of the buffer to empty */
  933. {
  934.    int i;
  935.  
  936. #if BS_FORMAT == BINARY
  937.    for (i=bs->buf_size-1;i>=minimum;i--)
  938.     fwrite(&bs->buf[i], sizeof(unsigned char), 1, bs->pt);
  939. #else
  940.    for (i=bs->buf_size-1;i>=minimum;i--) {
  941.     char val[2];
  942.     val[0] = he[((bs->buf[i] >> 4) & 0x0F)];
  943.     val[1] = he[(bs->buf[i] & 0x0F)];
  944.     fwrite(val, sizeof(char), 2, bs->pt);
  945.    }
  946. #endif
  947.  
  948.    for (i=minimum-1; i>=0; i--)
  949.     bs->buf[bs->buf_size - minimum + i] = bs->buf[i];
  950.  
  951.    bs->buf_byte_idx = bs->buf_size -1 - minimum;
  952.    bs->buf_bit_idx = 8;
  953. }
  954.  
  955.  
  956. /*
  957.  * Open the device to write the bit stream into it
  958.  */
  959. void open_bit_stream_w(
  960.     Bit_stream_struc *bs,   /* bit stream structure */
  961.     char *bs_filenam,       /* name of the bit stream file */
  962.     int size)               /* size of the buffer */
  963. {
  964.     if ((bs->pt = fopen(bs_filenam, "wb")) == NULL) {
  965.     fprintf(stderr, "Could not create \"%s\"\n", bs_filenam);
  966.     exit(1);
  967.     }
  968.     alloc_buffer(bs, size);
  969.     bs->buf_byte_idx = size-1;
  970.     bs->buf_bit_idx=8;
  971.     bs->totbit=0;
  972.     bs->mode = WRITE_MODE;
  973.     bs->eob = FALSE;
  974.     bs->eobs = FALSE;
  975. }
  976.  
  977.  
  978. /*
  979.  * Open the device to read the bit stream from it
  980.  */
  981. void open_bit_stream_r(
  982.     Bit_stream_struc *bs,   /* bit stream structure */
  983.     char *bs_filenam,       /* name of the bit stream file */
  984.     int size)               /* size of the buffer */
  985. {
  986.     unsigned long    n;
  987.     unsigned char    flag = 1;
  988.     unsigned char    val;
  989.     unsigned char    ungetBuf[10]; /* max # chars we can ungetc()*/
  990.     int            nungetc;
  991.  
  992.     if (strcmp(bs_filenam, "-") == 0) {
  993.     /* Read stdin*/
  994.     if ((bs->pt = fdopen(0, "rb")) == NULL) {
  995.         fprintf(stderr, "%s: could not open stdin\n", programName);
  996.         exit(1);
  997.     }
  998.     } else {
  999.     /* Read a file*/
  1000.     if ((bs->pt = fopen(bs_filenam, "rb")) == NULL) {
  1001.         fprintf(stderr, "%s: could not find \"%s\"\n",
  1002.             programName, bs_filenam);
  1003.         exit(1);
  1004.     }
  1005.     }
  1006.  
  1007.     nungetc = 0;
  1008.     do {
  1009.     n = fread(&val, sizeof(unsigned char), 1, bs->pt);
  1010.     ungetBuf[nungetc++] = val;    /* save for pushback to stream*/
  1011.  
  1012.     switch (val) {
  1013.     case 0x30:
  1014.     case 0x31:
  1015.     case 0x32:
  1016.     case 0x33:
  1017.     case 0x34:
  1018.     case 0x35:
  1019.     case 0x36:
  1020.     case 0x37:
  1021.     case 0x38:
  1022.     case 0x39:
  1023.     case 0x41:
  1024.     case 0x42:
  1025.     case 0x43:
  1026.     case 0x44:
  1027.     case 0x45:
  1028.     case 0x46:
  1029.     case 0xa:  /* \n */
  1030.     case 0xd:  /* cr */
  1031.     case 0x1a:  /* sub */
  1032.         break;
  1033.     default: /* detection of an binary character */
  1034.         flag--;
  1035.         break;
  1036.     }
  1037.     } while ((flag & n) && nungetc < 10);
  1038.  
  1039.     if (flag) {
  1040.     if (Arguments.verbose)
  1041.         fprintf(stderr, "The bit stream file %s is an ascii file\n", bs_filenam);
  1042.     bs->format = ASCII;
  1043.     } else {
  1044.     if (Arguments.verbose) {
  1045.         if (strcmp(bs_filenam, "-") == 0)
  1046.         fprintf(stderr, "The input bit stream is binary\n");
  1047.         else
  1048.         fprintf(stderr, "The bit stream file \"%s\" is a binary file\n",
  1049.                 bs_filenam);
  1050.     }
  1051.     bs->format = BINARY;
  1052.     }
  1053.  
  1054.     if (strcmp(bs_filenam, "-") == 0) {
  1055.     /* Cannot rewind a pipe, push back character instead.*/
  1056.     /* Only four bytes are actually guaranteed to ungetc().*/
  1057.     while (nungetc > 0)
  1058.         ungetc(ungetBuf[--nungetc], bs->pt);
  1059.  
  1060.     } else {
  1061.     fclose(bs->pt);
  1062.     if ((bs->pt = fopen(bs_filenam, "rb")) == NULL) {
  1063.         fprintf(stderr, "%s: could not find \"%s\"\n",
  1064.             programName, bs_filenam);
  1065.         exit(1);
  1066.     }
  1067.     }
  1068.  
  1069.     alloc_buffer(bs, size);
  1070.     bs->buf_byte_idx=0;
  1071.     bs->buf_bit_idx=0;
  1072.     bs->totbit=0;
  1073.     bs->mode = READ_MODE;
  1074.     bs->eob = FALSE;
  1075.     bs->eobs = FALSE;
  1076. }
  1077.  
  1078. /* Close the device containing the bit stream after a read process*/
  1079. void close_bit_stream_r(Bit_stream_struc *bs)   /* bit stream structure */
  1080. {
  1081.    fclose(bs->pt);
  1082.    desalloc_buffer(bs);
  1083. }
  1084.  
  1085. /* Close the device containing the bit stream after a write process*/
  1086. void close_bit_stream_w(Bit_stream_struc *bs)   /* bit stream structure */
  1087. {
  1088.    empty_buffer(bs, bs->buf_byte_idx);
  1089.    fclose(bs->pt);
  1090.    desalloc_buffer(bs);
  1091. }
  1092.  
  1093. /* Open and initialize the buffer; */
  1094. void alloc_buffer(
  1095.     Bit_stream_struc *bs,   /* bit stream structure */
  1096.     int size)
  1097. {
  1098.    bs->buf = (unsigned char FAR *) mem_alloc(size*sizeof(unsigned
  1099.               char), "buffer");
  1100.    bs->buf_size = size;
  1101. }
  1102.  
  1103. /* Empty and close the buffer */
  1104. void desalloc_buffer(Bit_stream_struc *bs)   /* bit stream structure */
  1105. {
  1106.    free(bs->buf);
  1107. }
  1108.  
  1109. int putmask[9] = {0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
  1110. int clearmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x0};
  1111.  
  1112. void back_track_buffer(        /* goes back N bits in the buffer */
  1113.     Bit_stream_struc *bs,   /* bit stream structure */
  1114.     int N)
  1115. {
  1116.    int    tmp = N - (N/8)*8;
  1117.    int    i;
  1118.  
  1119.    bs->totbit -= N;
  1120.    for (i=bs->buf_byte_idx;i< bs->buf_byte_idx+N/8-1;i++) bs->buf[i] = 0;
  1121.    bs->buf_byte_idx += N/8;
  1122.    if ( (tmp + bs->buf_bit_idx) <= 8) {
  1123.       bs->buf_bit_idx += tmp;
  1124.    }
  1125.    else {
  1126.       bs->buf_byte_idx ++;
  1127.       bs->buf_bit_idx += (tmp - 8);
  1128.    }
  1129.    bs->buf[bs->buf_byte_idx] &= clearmask[bs->buf_bit_idx];
  1130. }
  1131.  
  1132.  
  1133. int mask[8]={0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
  1134.  
  1135. /*
  1136.  * Read 1 bit from the bit stream
  1137.  */
  1138. unsigned int get1bit(Bit_stream_struc *bs)   /* bit stream structure */
  1139. {
  1140.     unsigned int bit;
  1141.     int         i;
  1142.  
  1143.     bs->totbit++;
  1144.  
  1145.     if (!bs->buf_bit_idx) {
  1146.     bs->buf_bit_idx = 8;
  1147.     bs->buf_byte_idx--;
  1148.     if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  1149.         if (bs->eob)
  1150.         bs->eobs = TRUE;
  1151.         else {
  1152.         for (i = bs->buf_byte_idx; i >= 0; i--)
  1153.             bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  1154.         refill_buffer(bs);
  1155.         bs->buf_byte_idx = bs->buf_size-1;
  1156.         }
  1157.     }
  1158.    }
  1159.    bit = bs->buf[bs->buf_byte_idx] & mask[bs->buf_bit_idx-1];
  1160.    bit = bit >> (bs->buf_bit_idx-1);
  1161.    bs->buf_bit_idx--;
  1162.  
  1163.    return bit;
  1164. }
  1165.  
  1166. /*
  1167.  * Write 1 bit from the bit stream
  1168.  */
  1169. void put1bit(
  1170.     Bit_stream_struc *bs,   /* bit stream structure */
  1171.     int bit)            /* bit to write into the buffer */
  1172. {
  1173.    bs->totbit++;
  1174.  
  1175.    bs->buf[bs->buf_byte_idx] |= (bit&0x1) << (bs->buf_bit_idx-1);
  1176.    bs->buf_bit_idx--;
  1177.    if (!bs->buf_bit_idx) {
  1178.        bs->buf_bit_idx = 8;
  1179.        bs->buf_byte_idx--;
  1180.        if (bs->buf_byte_idx < 0)
  1181.           empty_buffer(bs, MINIMUM);
  1182.        bs->buf[bs->buf_byte_idx] = 0;
  1183.    }
  1184. }
  1185.  
  1186. /*
  1187.  * Look ahead for the next N bits from the bit stream
  1188.  */
  1189. unsigned long look_ahead(
  1190.     Bit_stream_struc    *bs,    /* bit stream structure */
  1191.     int             N)    /* number of bits to read from the bit stream */
  1192. {
  1193.     unsigned long    val = 0;
  1194.     int            j = N;
  1195.     int            k, tmp;
  1196.     int            bit_idx = bs->buf_bit_idx;
  1197.     int            byte_idx = bs->buf_byte_idx;
  1198.  
  1199. #ifndef OPTIMIZE
  1200.     if (N > MAX_LENGTH)
  1201.     fprintf(stderr, "Cannot read or write more than %d bits at a time.\n",
  1202.             MAX_LENGTH);
  1203. #endif
  1204.  
  1205.     while (j > 0) {
  1206.     if (!bit_idx) {
  1207.         bit_idx = 8;
  1208.         byte_idx--;
  1209.     }
  1210.     k = MIN(j, bit_idx);
  1211.     tmp = bs->buf[byte_idx]&putmask[bit_idx];
  1212.     tmp = tmp >> (bit_idx-k);
  1213.     val |= tmp << (j-k);
  1214.     bit_idx -= k;
  1215.     j -= k;
  1216.     }
  1217.     return val;
  1218. }
  1219.  
  1220. /*
  1221.  * Read N bit from the bit stream
  1222.  */
  1223. unsigned long getbits(
  1224.     Bit_stream_struc    *bs,    /* bit stream structure */
  1225.     int             N)    /* number of bits to read from the bit stream */
  1226. {
  1227.     unsigned long    val = 0;
  1228.     int            i;
  1229.     int            j = N;
  1230.     int            k;
  1231. #ifndef OPTIMIZE
  1232.     int            tmp;
  1233.  
  1234.     if (N > MAX_LENGTH)
  1235.     fprintf(stderr, "Cannot read/write more than %d bits at a time\n", MAX_LENGTH);
  1236. #endif
  1237.  
  1238.     bs->totbit += N;
  1239.     while (j > 0) {
  1240.     if (!bs->buf_bit_idx) {
  1241.         bs->buf_bit_idx = 8;
  1242.         bs->buf_byte_idx--;
  1243.         if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  1244.         if (bs->eob)
  1245.             bs->eobs = TRUE;
  1246.         else {
  1247.             for (i=bs->buf_byte_idx; i>=0;i--)
  1248.             bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  1249.             refill_buffer(bs);
  1250.             bs->buf_byte_idx = bs->buf_size-1;
  1251.         }
  1252.         }
  1253.     }
  1254.     k = MIN(j, bs->buf_bit_idx);
  1255. #ifdef OPTIMIZE
  1256.     val |= ((int)(bs->buf[bs->buf_byte_idx] & putmask[bs->buf_bit_idx]) >>
  1257.         (bs->buf_bit_idx - k)) << (j - k);
  1258. #else
  1259.     tmp = bs->buf[bs->buf_byte_idx] & putmask[bs->buf_bit_idx];
  1260.     tmp = tmp >> (bs->buf_bit_idx-k);
  1261.     val |= tmp << (j-k);
  1262. #endif
  1263.     bs->buf_bit_idx -= k;
  1264.     j -= k;
  1265.     }
  1266.     return val;
  1267. }
  1268.  
  1269.  
  1270. /* Write N bits into the bit stream */
  1271. void putbits(
  1272.     Bit_stream_struc *bs,   /* bit stream structure */
  1273.     unsigned int val,       /* val to write into the buffer */
  1274.     int N)                  /* number of bits of val */
  1275. {
  1276.  int    j = N;
  1277.  int    k, tmp;
  1278.  
  1279.  if (N > MAX_LENGTH)
  1280.     fprintf(stderr, "Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1281.  
  1282.  bs->totbit += N;
  1283.  while (j > 0) {
  1284.    k = MIN(j, bs->buf_bit_idx);
  1285.    tmp = val >> (j-k);
  1286.    bs->buf[bs->buf_byte_idx] |= (tmp&putmask[k]) << (bs->buf_bit_idx-k);
  1287.    bs->buf_bit_idx -= k;
  1288.    if (!bs->buf_bit_idx) {
  1289.        bs->buf_bit_idx = 8;
  1290.        bs->buf_byte_idx--;
  1291.        if (bs->buf_byte_idx < 0)
  1292.           empty_buffer(bs, MINIMUM);
  1293.        bs->buf[bs->buf_byte_idx] = 0;
  1294.    }
  1295.    j -= k;
  1296.  }
  1297. }
  1298.  
  1299. /* Write N bits byte aligned into the bit stream */
  1300. void byte_ali_putbits(
  1301.     Bit_stream_struc *bs,   /* bit stream structure */
  1302.     unsigned int val,       /* val to write into the buffer */
  1303.     int N)                  /* number of bits of val */
  1304. {
  1305.  unsigned long aligning;
  1306.  
  1307.  if (N > MAX_LENGTH)
  1308.     fprintf(stderr, "Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1309.  aligning = sstell(bs)%8;
  1310.  if (aligning)
  1311.      putbits(bs, (unsigned int)0, (int)(8-aligning)); 
  1312.  
  1313.  putbits(bs, val, N);
  1314. }
  1315.  
  1316. /* Read the next bute aligned N bits from the bit stream */
  1317. unsigned long byte_ali_getbits(
  1318.     Bit_stream_struc *bs,   /* bit stream structure */
  1319.     int N)                  /* number of bits of val */
  1320. {
  1321.  unsigned long aligning;
  1322.  
  1323.  if (N > MAX_LENGTH)
  1324.     fprintf(stderr, "Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1325.  aligning = sstell(bs)%8;
  1326.  if (aligning)
  1327.     getbits(bs, (int)(8-aligning));
  1328.  
  1329.  return(getbits(bs, N));
  1330. }
  1331.  
  1332. /* Return the current bit stream length (in bits)*/
  1333. unsigned long sstell(Bit_stream_struc *bs)   /* bit stream structure */
  1334. {
  1335.   return(bs->totbit);
  1336. }
  1337.  
  1338. /* Return the status of the bit stream */
  1339. /* returns 1 if end of bit stream was reached */
  1340. /* returns 0 if end of bit stream was not reached */
  1341. int end_bs(Bit_stream_struc *bs)   /* bit stream structure */
  1342. {
  1343.   return(bs->eobs);
  1344. }
  1345.  
  1346.  
  1347. /*
  1348.  * This function seeks for a byte aligned sync word in the bit stream and
  1349.  * places the bit stream pointer right after the sync.
  1350.  * This function returns 1 if the sync was found otherwise it returns 0
  1351.  */
  1352. int seek_sync(
  1353.     Bit_stream_struc    *bs,    /* bit stream structure */
  1354.     long         sync,    /* sync word maximum 32 bits */
  1355.     int             N)    /* sync word length */
  1356. {
  1357.     unsigned long aligning;
  1358.     unsigned long val;
  1359. #ifdef OPTIMIZE
  1360.     /* main() *always* calls this routine with N = SYNC_WORD_LNGTH = 12*/
  1361.     /* This is really easy to optimize :-)*/
  1362.     long maxi = 4095;    /*(long)pow(2.0, (float)N) - 1;*/
  1363.  
  1364.     aligning = bs->totbit & (ALIGNING - 1);    /* ALIGNING equals 8*/
  1365.     if (aligning)
  1366.     getbits(bs, ALIGNING-aligning);
  1367. #else
  1368.     long maxi = (long)pow(2.0, (float)N) - 1;
  1369.  
  1370.     aligning = sstell(bs)%ALIGNING;
  1371.     if (aligning)
  1372.     getbits(bs, (int)(ALIGNING-aligning));
  1373. #endif
  1374.  
  1375.     val = getbits(bs, N);
  1376.     while (((val & maxi) != sync) && (!end_bs(bs))) {
  1377.         val <<= ALIGNING;
  1378.         val |= getbits(bs, ALIGNING);
  1379.     }
  1380.  
  1381.     if (end_bs(bs))
  1382.     return 0;
  1383.     else
  1384.     return 1;
  1385. }
  1386.  
  1387. /*****************************************************************************
  1388. *
  1389. *  End of bit_stream.c package
  1390. *
  1391. *****************************************************************************/
  1392.  
  1393. /*****************************************************************************
  1394. *
  1395. *  CRC error protection package
  1396. *
  1397. *****************************************************************************/
  1398.  
  1399. void I_CRC_calc(
  1400.     frame_params *fr_ps,
  1401.     unsigned int bit_alloc[2][SBLIMIT],
  1402.     unsigned int *crc)
  1403. {
  1404.         int i, k;
  1405.         layer *info = fr_ps->header;
  1406.         int stereo  = fr_ps->stereo;
  1407.         int jsbound = fr_ps->jsbound;
  1408.  
  1409.         *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  1410.         update_CRC(info->bitrate_index, 4, crc);
  1411.         update_CRC(info->sampling_frequency, 2, crc);
  1412.         update_CRC(info->padding, 1, crc);
  1413.         update_CRC(info->extension, 1, crc);
  1414.         update_CRC(info->mode, 2, crc);
  1415.         update_CRC(info->mode_ext, 2, crc);
  1416.         update_CRC(info->copyright, 1, crc);
  1417.         update_CRC(info->original, 1, crc);
  1418.         update_CRC(info->emphasis, 2, crc);
  1419.  
  1420.         for (i=0;i<SBLIMIT;i++)
  1421.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  1422.                         update_CRC(bit_alloc[k][i], 4, crc);
  1423. }
  1424.  
  1425. void II_CRC_calc(
  1426.     frame_params    *fr_ps,
  1427.     unsigned int     bit_alloc[2][SBLIMIT],
  1428.     unsigned int     scfsi[2][SBLIMIT],
  1429.     unsigned int    *crc)
  1430. {
  1431.     int         i, k;
  1432.     layer    *info = fr_ps->header;
  1433.     int         stereo  = fr_ps->stereo;
  1434.     int         sblimit = fr_ps->sblimit;
  1435.     int         jsbound = fr_ps->jsbound;
  1436.     al_table    *alloc = fr_ps->alloc;
  1437. #ifdef OPTIMIZE
  1438.     unsigned int lcrc = 0xffff;
  1439.  
  1440.     update_CRC(info->bitrate_index, 4, &lcrc);
  1441.     update_CRC(info->sampling_frequency, 2, &lcrc);
  1442.     update_CRC(info->padding, 1, &lcrc);
  1443.     update_CRC(info->extension, 1, &lcrc);
  1444.     update_CRC(info->mode, 2, &lcrc);
  1445.     update_CRC(info->mode_ext, 2, &lcrc);
  1446.     update_CRC(info->copyright, 1, &lcrc);
  1447.     update_CRC(info->original, 1, &lcrc);
  1448.     update_CRC(info->emphasis, 2, &lcrc);
  1449.  
  1450.     /* Combine loops into one*/
  1451.     for (i = 0; i < sblimit; i++)
  1452.     for (k = 0; k < stereo; k++) {
  1453.         if (bit_alloc[k][i])
  1454.         update_CRC(scfsi[k][i], 2, &lcrc);
  1455.         if (i < jsbound || k == 0)
  1456.         update_CRC(bit_alloc[k][i], (*alloc)[i][0].bits, &lcrc);
  1457.     }
  1458.     *crc = lcrc;    /* update once*/
  1459.  
  1460. #else
  1461.     /* Original code*/
  1462.  
  1463.     *crc = 0xffff;        /* changed from '0' 92-08-11 shn */
  1464.     update_CRC(info->bitrate_index, 4, crc);
  1465.     update_CRC(info->sampling_frequency, 2, crc);
  1466.     update_CRC(info->padding, 1, crc);
  1467.     update_CRC(info->extension, 1, crc);
  1468.     update_CRC(info->mode, 2, crc);
  1469.     update_CRC(info->mode_ext, 2, crc);
  1470.     update_CRC(info->copyright, 1, crc);
  1471.     update_CRC(info->original, 1, crc);
  1472.     update_CRC(info->emphasis, 2, crc);
  1473.  
  1474.     for (i = 0; i < sblimit; i++)
  1475.     for (k = 0; k < ((i < jsbound) ? stereo : 1); k++)
  1476.         update_CRC(bit_alloc[k][i], (*alloc)[i][0].bits, crc);
  1477.  
  1478.     for (i = 0; i < sblimit; i++)
  1479.     for (k = 0; k < stereo; k++)
  1480.         if (bit_alloc[k][i])
  1481.         update_CRC(scfsi[k][i], 2, crc);
  1482. #endif /* OPTIMIZE*/
  1483. }
  1484.  
  1485. void update_CRC(unsigned int data, unsigned int length, unsigned int *crc)
  1486. {
  1487.     unsigned int  masking, carry;
  1488.  
  1489.     masking = 1 << length;
  1490.  
  1491.     while((masking >>= 1)) {
  1492.     carry = *crc & 0x8000;
  1493.     *crc <<= 1;
  1494.     if (!carry ^ !(data & masking))
  1495.         *crc ^= CRC16_POLYNOMIAL;
  1496.     }
  1497.     *crc &= 0xffff;
  1498. }
  1499.  
  1500. /*****************************************************************************
  1501. *
  1502. *  End of CRC error protection package
  1503. *
  1504. *****************************************************************************/
  1505.  
  1506. #ifdef  MACINTOSH
  1507. /*****************************************************************************
  1508. *
  1509. *  Set Macintosh file attributes.
  1510. *
  1511. *****************************************************************************/
  1512.  
  1513. void    set_mac_file_attr(fileName, vRefNum, creator, fileType)
  1514. char    fileName[MAX_NAME_SIZE];
  1515. short   vRefNum;
  1516. OsType  creator;
  1517. OsType  fileType;
  1518. {
  1519.  
  1520. short   theFile;
  1521. char    pascal_fileName[MAX_NAME_SIZE];
  1522. FInfo   fndrInfo;
  1523.  
  1524.     CtoPstr(strcpy(pascal_fileName, fileName));
  1525.  
  1526.     FSOpen(pascal_fileName, vRefNum, &theFile);
  1527.     GetFInfo(pascal_fileName, vRefNum, &fndrInfo);
  1528.     fndrInfo.fdCreator = creator;
  1529.     fndrInfo.fdType = fileType;
  1530.     SetFInfo(pascal_fileName, vRefNum, &fndrInfo);
  1531.     FSClose(theFile);
  1532.  
  1533. }
  1534. #endif /* MACINTOSH*/
  1535.  
  1536.  
  1537. #ifdef MS_DOS
  1538. /* ------------------------------------------------------------------------
  1539. new_ext()
  1540. Puts a new extension name on a file name <filename>.
  1541. Removes the last extension name, if any.
  1542. 1992-08-19, 1995-06-12 shn
  1543. ------------------------------------------------------------------------ */
  1544. char *new_ext(char *filename, char *extname)
  1545. {
  1546.   int found, dotpos;
  1547.   static char newname[80];
  1548.  
  1549.   /* First, strip the extension */
  1550.   dotpos=strlen(filename); found=0;
  1551.   do
  1552.   {
  1553.     switch (filename[dotpos])
  1554.     {
  1555.       case '.' : found=1; break;
  1556.       case '\\':                  /* used by MS-DOS */
  1557.       case '/' :                  /* used by UNIX */
  1558.       case ':' : found=-1; break; /* used by MS-DOS in drive designation */
  1559.       default  : dotpos--; if (dotpos<0) found=-1; break;
  1560.     }
  1561.   } while (found==0);
  1562.   if (found==-1) strcpy(newname,filename);
  1563.   if (found== 1) strncpy(newname,filename,dotpos); newname[dotpos]='\0';
  1564.   strcat(newname,extname);
  1565.   return(newname);
  1566. }
  1567. #endif /* MS_DOS*/
  1568.  
  1569. #define BUFSIZE 4096
  1570. /* Assembly routines require these to be global*/
  1571. unsigned long offset,totbit=0, buf_byte_idx=0;
  1572. unsigned int buf[BUFSIZE];
  1573. unsigned int buf_bit_idx=8;
  1574.  
  1575. /* Return the current bit stream length (in bits) */
  1576. unsigned long hsstell()
  1577. {
  1578.   return(totbit);
  1579. }
  1580.  
  1581. extern int putmask[9];
  1582.  
  1583. /*
  1584.  * read N bit from the bit stream
  1585.  */
  1586. unsigned long hgetbits(int N)  /* number of bits to read from the bit stream */
  1587. {
  1588.     unsigned long    val = 0;
  1589.     int            j = N;
  1590.     int            k;
  1591.  
  1592. #ifndef OPTIMIZE
  1593.     int            tmp;
  1594. #endif
  1595.  
  1596.     /*
  1597.      * if (N > MAX_LENGTH)
  1598.      *    fprintf(stderr, "Cannot read or write more than %d bits at a time.\n",
  1599.      *            MAX_LENGTH);
  1600.      */
  1601.     totbit += N;
  1602.     while (j > 0) {
  1603.     if (!buf_bit_idx) {
  1604.         buf_bit_idx = 8;
  1605.         buf_byte_idx++;
  1606.         if (buf_byte_idx > offset) {
  1607.         fprintf(stderr, "Buffer overflow !!\n");exit(3);
  1608.         }
  1609.     }
  1610.     k = MIN(j, buf_bit_idx);
  1611. #ifdef OPTIMIZE
  1612.     val |= ((buf[buf_byte_idx & (BUFSIZE-1)] & putmask[buf_bit_idx]) >>
  1613.         (buf_bit_idx - k)) << (j - k);
  1614. #else
  1615.     tmp = buf[buf_byte_idx%BUFSIZE]&putmask[buf_bit_idx];
  1616.     tmp = tmp >> (buf_bit_idx-k);
  1617.     val |= tmp << (j-k);
  1618. #endif
  1619.     buf_bit_idx -= k;
  1620.     j -= k;
  1621.     }
  1622.     return(val);
  1623. }
  1624.  
  1625. unsigned int hget1bit()
  1626. {
  1627. #ifdef OPTIMIZE
  1628.     unsigned int val;
  1629.  
  1630.     totbit++;
  1631.     if (buf_bit_idx == 0) {
  1632.     buf_bit_idx = 8;
  1633.     buf_byte_idx++;
  1634.     if (buf_byte_idx > offset) {
  1635.         fprintf(stderr, "Buffer overflow!!\n");
  1636.         exit(3);
  1637.     }
  1638.     }
  1639.     val = ((buf[buf_byte_idx & (BUFSIZE-1)] & putmask[buf_bit_idx]) >>
  1640.             (buf_bit_idx - 1));
  1641.     buf_bit_idx--;
  1642.  
  1643.     return(val);
  1644. #else
  1645.     return(hgetbits(1));
  1646. #endif
  1647. }
  1648.  
  1649.  
  1650. /* Write N bits into the bit stream */
  1651. void hputbuf(
  1652.     unsigned int val,       /* val to write into the buffer */
  1653.     int N)                  /* number of bits of val */
  1654. {
  1655.   if (N != 8) { fprintf(stderr, "Not Supported yet!!\n"); exit(-3); }
  1656.   buf[offset % BUFSIZE] = val;
  1657.   offset++;
  1658. }
  1659.  
  1660. void rewindNbits(int N)
  1661. {
  1662.    totbit -= N;
  1663.    buf_bit_idx += N;
  1664.    while( buf_bit_idx >= 8 )
  1665.    {  buf_bit_idx -= 8;
  1666.       buf_byte_idx--;
  1667.    }
  1668. }
  1669.  
  1670. void rewindNbytes(int N)
  1671. {
  1672.    totbit -= N*8;
  1673.    buf_byte_idx -= N;
  1674. }
  1675.